package cn.iocoder.yudao.module.currency.api.rate;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.currency.enums.ErrorCodeConstants.EXCHANGE_RATE_NOT_EXISTS;

import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.currency.api.rate.dto.ExchangeRateRespDTO;
import cn.iocoder.yudao.module.currency.config.PaymentCurrencyConfig;
import cn.iocoder.yudao.module.currency.service.rate.ExchangeRateQueryService;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

/**
 * @author cai
 * @date 2024/03/06 00:01
 */
@Service
@Validated
public class ExchangeRateApiImpl implements ExchangeRateApi {

    @Resource
    private ExchangeRateQueryService exchangeRateQueryService;

    @Resource
    private PaymentCurrencyConfig paymentCurrencyConfig;

    @Override
    public ExchangeRateRespDTO getExchangeRate(String currencyCode) {
        return BeanUtils.toBean(exchangeRateQueryService.getExchangeRate(currencyCode), ExchangeRateRespDTO.class);
    }

    @Override
    public ExchangeRateRespDTO getExchangeRate(String baseCode, String targetCode) {
        return BeanUtils.toBean(exchangeRateQueryService.getExchangeRate(baseCode, targetCode), ExchangeRateRespDTO.class);
    }

    @Override
    public List<ExchangeRateRespDTO> getAvailableCurrencyList() {
        return BeanUtils.toBean(exchangeRateQueryService.getAvailableCurrencyList(null, null, null), ExchangeRateRespDTO.class);
    }

    @Override
    public List<ExchangeRateRespDTO> getListByCode(Collection<String> currencyCodes) {
        return BeanUtils.toBean(exchangeRateQueryService.getListByCode(currencyCodes), ExchangeRateRespDTO.class);
    }

    @Override
    public String getPaymentCurrency() {
        return paymentCurrencyConfig.getCode();
    }

    @Override
    public Integer calculateWithCurrency(Integer value, String currencyCode) {
        ExchangeRateRespDTO exchangeRate = getExchangeRate(currencyCode);
        if (Objects.isNull(exchangeRate)) {
            throw exception(EXCHANGE_RATE_NOT_EXISTS);
            //throw new IllegalArgumentException("货币类型[" + currencyCode + "]不支持");
        }
        BigDecimal rate = exchangeRate.getExchangeRate();
        return calculateWithRate(value, rate);
    }

    @Override
    public Integer calculateWithRate(Integer value, BigDecimal rate) {
        if (value == null){
            return null;
        }
        BigDecimal paymentPrice = BigDecimal.valueOf(value).divide(rate, 0, RoundingMode.HALF_UP);
        return paymentPrice.intValue();
    }

    @Override
    public BigDecimal reverseRate(BigDecimal rate) {
        return BigDecimal.ONE.divide(rate, 6, RoundingMode.HALF_UP);
    }

}
